import os
import time
from multiprocessing import Lock

from flask import Flask, render_template, request,session
import logging

from RWLock import RWLock

app = Flask(__name__)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
log.disabled = True
app.config['SECRET_KEY'] = os.urandom(24)

lock = RWLock()

@app.route('/')
def index():  # put application's code here
    return render_template("index.html")

@app.route('/list')
def list():  # put application's code here

    ymd = time.strftime("%Y-%m-%d", time.localtime())

    if "submit_length"  not in session or  session["submit_length"] < 20:
        return render_template("list.html", bad="未提交数据，或者提交数据质量太差，无权查看")
    if "submit_date" not in session or session["submit_date"] != ymd:
        return render_template("list.html", bad="未提交数据，或者提交数据质量太差，无权查看")

    folder = "submit_data/"+(time.strftime("%Y-%m-%d", time.localtime()))
    path=folder+"/"+"good.txt"
    try:
        lock.read_acquire()
        with open(path, mode='r',encoding='utf-8') as file_obj:
            good = file_obj.read()
            good = good.rstrip()
            good=good.replace('\n',"<br/>")

        path = folder + "/" + "bad.txt"
        with open(path, mode='r',encoding='utf-8') as file_obj:
            bad = file_obj.read()
            bad = bad.rstrip()
            bad=bad.replace('\n', "<br/>")
    except Exception as e:
        lock.read_release()
        return render_template("list.html", good=e)

    lock.read_release()
    return render_template("list.html",good=good,bad=bad,escapeHTML=False)


@app.route('/submitdata',methods=['post'])
def submitdata():  # put application's code here
    ymd = time.strftime("%Y-%m-%d", time.localtime())
    good = request.form.get('good')
    bad = request.form.get('bad')
    length=len(good) +len(bad)

    try:
        lock.write_acquire()
        if not os.path.exists("submit_data"):
            os.mkdir("submit_data")
        folder = "submit_data/"+(ymd)
        if not os.path.exists(folder):
            os.mkdir(folder)
        path=folder+"/"+"good.txt"
        with open(path, mode='a', encoding='utf-8') as goodfile:
            goodfile.write(good)
            goodfile.write("<hr/>\n")
        path=folder+"/"+"bad.txt"
        with open(path, mode='a', encoding='utf-8') as badfile:
            badfile.write(bad)
            badfile.write("<hr/>\n")

        session['submit_length']=length
        session['submit_date'] = ymd
    except Exception as e:
        lock.write_release()
        return render_template("list.html", good=e)

    lock.write_release()
    return  render_template("submitok.html")

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8081)
